<template>
  <div class="dashboard-container">
    <!-- 侧边栏 -->
    <aside class="sidebar">
      <div class="logo">
        <h2>管理后台</h2>
      </div>
      <nav class="nav-menu">
        <div class="menu-item" @click="navigateTo('/dashboard')">
          <span>📊</span>
          <span>数据统计</span>
        </div>
        <div class="menu-item" @click="navigateTo('/user-audit')">
          <span>👥</span>
          <span>用户审核</span>
        </div>
        <div class="menu-item" @click="navigateTo('/user-management')">
          <span>👤</span>
          <span>用户管理</span>
        </div>
        <div class="menu-item" @click="navigateTo('/team-management')">
          <span>⚡</span>
          <span>队伍管理</span>
        </div>
        <div class="menu-item" @click="navigateTo('/homepage-editor')">
          <span>🏠</span>
          <span>主页编辑</span>
        </div>
        <div class="menu-item active" @click="navigateTo('/system-notifications')">
          <span>📢</span>
          <span>通知管理</span>
        </div>
        <div class="menu-item" @click="navigateTo('/news-management')">
          <span>📰</span>
          <span>新闻管理</span>
        </div>
        <div class="menu-item" @click="navigateTo('/event-management')">
          <span>🏆</span>
          <span>赛事管理</span>
        </div>
      </nav>
      <div class="user-info">
        <div class="user-avatar">👤</div>
        <div class="user-details">
          <div class="user-name">{{ adminName }}</div>
          <div class="user-role">账号</div>
        </div>
        <button class="logout-btn" @click="handleLogout">
          退出登录
        </button>
      </div>
    </aside>

    <!-- 主要内容区域 -->
    <main class="content">
      <div class="page-header">
        <h2>{{ isEditing ? '编辑通知' : '发布通知' }}</h2>
        <div class="header-actions">
          <button class="back-btn" @click="goBack">返回列表</button>
        </div>
      </div>

      <!-- 通知表单 -->
      <div class="notification-form">
        <div class="form-section">
          <div class="form-group">
            <label class="required">通知标题</label>
            <input 
              v-model="notificationForm.title" 
              type="text" 
              class="form-input"
              placeholder="请输入通知标题"
              maxlength="200"
            />
            <div class="char-count">{{ notificationForm.title.length }}/200</div>
          </div>

          <div class="form-group">
            <label>通知摘要</label>
            <textarea 
              v-model="notificationForm.summary" 
              class="form-textarea"
              rows="3"
              placeholder="请输入通知摘要（可选，用于列表展示）"
              maxlength="500"
            ></textarea>
            <div class="char-count">{{ notificationForm.summary.length }}/500</div>
          </div>


          <div class="form-group">
            <label class="required">通知内容</label>
            <div class="editor-container">
              <!-- wangEditor 富文本编辑器 -->
              <Toolbar
                style="border-bottom: 1px solid #ccc"
                :editor="editorRef"
                :defaultConfig="toolbarConfig"
                :mode="mode"
              />
              <Editor
                style="height: 400px; overflow-y: hidden;"
                v-model="notificationForm.content"
                :defaultConfig="editorConfig"
                :mode="mode"
                @onCreated="handleCreated"
              />
            </div>
          </div>

        </div>

        <!-- 操作按钮 -->
        <div class="form-actions">
          <button class="cancel-btn" @click="goBack">取消</button>
          <button class="draft-btn" @click="saveDraft" :disabled="saving">
            {{ saving && saveType === 'draft' ? '保存中...' : '保存草稿' }}
          </button>
          <button class="publish-btn" @click="publishNotification" :disabled="saving || !canPublish">
            {{ saving && saveType === 'publish' ? '发布中...' : '立即发布' }}
          </button>
        </div>
      </div>
    </main>

    <!-- 消息提示 -->
    <div v-if="showMessage" class="message-toast" :class="messageType">
      {{ messageText }}
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, shallowRef, onBeforeUnmount } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useTokenStore } from '@/stores/token.js'
import { useAdminStore } from '@/stores/admin.js'
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import {
  createSystemNotificationService,
  updateSystemNotificationService,
  getSystemNotificationService
} from '@/api/admin.js'

const router = useRouter()
const route = useRoute()
const tokenStore = useTokenStore()
const adminStore = useAdminStore()

// 管理员姓名
const adminName = computed(() => {
  return adminStore.getAdminName()
})

// 编辑状态
const isEditing = computed(() => {
  return !!route.params.id
})

// 表单数据
const notificationForm = ref({
  title: '',
  summary: '',
  content: ''
})

// 状态管理
const saving = ref(false)
const saveType = ref('')

// wangEditor 配置
const editorRef = shallowRef()
const mode = 'default' // 或 'simple'

// 获取管理员token
const getAdminToken = () => {
  return tokenStore.token || localStorage.getItem('token') || ''
}

const toolbarConfig = {}

// 动态生成编辑器配置
const getEditorConfig = () => ({
  placeholder: '请输入通知内容...',
  MENU_CONF: {
    // 配置上传图片
    uploadImage: {
      // 上传图片配置
      server: '/api/adminUser/system-notifications/upload',

      // form-data fieldName，默认值 'wangeditor-uploaded-image'
      fieldName: 'file',

      // 单个文件的最大体积限制，默认为 2M
      maxFileSize: 10 * 1024 * 1024, // 10M

      // 最多可上传几个文件，默认为 100
      maxNumberOfFiles: 1,

      // 选择文件时的类型限制，默认为 ['image/*']
      allowedFileTypes: ['image/*'],

      // 自定义上传参数，例如传递验证的 token 等
      meta: {
        // token: 'xxx',
        // otherKey: 'yyy'
      },

      // 将 meta 拼接到 url 参数中，默认 false
      metaWithUrl: false,

      // 自定义增加 http  header
      headers: {
        'Authorization': getAdminToken()
      },

      // 跨域是否传递 cookie ，默认为 false
      withCredentials: false,

      // 超时时间，默认为 10 秒
      timeout: 30 * 1000, // 30 秒

      // 上传之前触发
      onBeforeUpload(file) {
        console.log('上传图片之前', file)
        return file // 返回 file 继续上传，返回 false 终止上传
      },

      // 上传进度的回调函数
      onProgress(progress) {
        console.log('上传进度', progress)
      },

      // 单个文件上传成功之后
      onSuccess(file, res) {
        console.log('上传成功', file, res)
      },

      // 单个文件上传失败
      onFailed(file, res) {
        console.log('上传失败', file, res)
        showMessageToast('图片上传失败：' + (res.message || '未知错误'), 'error')
      },

      // 上传错误，或者触发 timeout 超时
      onError(file, err, res) {
        console.log('上传出错', file, err, res)
        showMessageToast('图片上传出错：' + (err.message || '网络错误'), 'error')
      },

      // 自定义插入图片
      customInsert(res, insertFn) {
        // res 即服务端的返回结果
        console.log('自定义插入图片', res)

        // 从 res 中找到 url alt href ，然后插入图片
        if (res.code === 200 && res.data && res.data.url) {
          insertFn(res.data.url, res.data.originalName || '图片', res.data.url)
          showMessageToast('图片上传成功')
        } else {
          showMessageToast('图片上传失败：' + (res.message || '未知错误'), 'error')
        }
      }
    }
  }
})

const editorConfig = getEditorConfig()

// 编辑器创建回调
const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}

// 消息提示
const showMessage = ref(false)
const messageText = ref('')
const messageType = ref('success')

// 验证是否可以发布
const canPublish = computed(() => {
  return notificationForm.value.title.trim() && notificationForm.value.content.trim()
})

// 导航到指定路由
const navigateTo = (path) => {
  router.push(path)
}

// 退出登录
const handleLogout = () => {
  tokenStore.removeToken()
  adminStore.clearAdminInfo()
  router.push('/login')
}

// 返回列表
const goBack = () => {
  router.push('/system-notifications')
}

// 显示消息
const showMessageToast = (text, type = 'success') => {
  messageText.value = text
  messageType.value = type
  showMessage.value = true
  setTimeout(() => {
    showMessage.value = false
  }, 3000)
}







// 保存草稿
const saveDraft = async () => {
  if (!notificationForm.value.title.trim()) {
    showMessageToast('请输入通知标题', 'error')
    return
  }

  saving.value = true
  saveType.value = 'draft'
  
  try {
    const data = {
      ...notificationForm.value,
      status: 0 // 草稿状态
    }

    let result
    if (isEditing.value) {
      result = await updateSystemNotificationService(route.params.id, data)
    } else {
      result = await createSystemNotificationService(data)
    }

    if (result.code === 200) {
      showMessageToast('草稿保存成功')
      if (!isEditing.value) {
        // 新建时保存草稿后跳转到编辑页面
        router.replace(`/edit-notification/${result.data.id}`)
      }
    } else {
      showMessageToast(result.message || '保存失败', 'error')
    }
  } catch (error) {
    console.error('保存草稿失败:', error)
    showMessageToast('保存失败，请稍后重试', 'error')
  } finally {
    saving.value = false
    saveType.value = ''
  }
}

// 发布通知
const publishNotification = async () => {
  if (!canPublish.value) {
    showMessageToast('请填写完整的通知信息', 'error')
    return
  }

  saving.value = true
  saveType.value = 'publish'
  
  try {
    const data = {
      ...notificationForm.value,
      status: 1 // 发布状态
    }

    let result
    if (isEditing.value) {
      result = await updateSystemNotificationService(route.params.id, data)
    } else {
      result = await createSystemNotificationService(data)
    }

    if (result.code === 200) {
      showMessageToast('通知发布成功')
      setTimeout(() => {
        router.push('/system-notifications')
      }, 1500)
    } else {
      showMessageToast(result.message || '发布失败', 'error')
    }
  } catch (error) {
    console.error('发布通知失败:', error)
    showMessageToast('发布失败，请稍后重试', 'error')
  } finally {
    saving.value = false
    saveType.value = ''
  }
}

// 加载通知详情（编辑模式）
const loadNotificationDetail = async () => {
  if (!isEditing.value) return

  try {
    const result = await getSystemNotificationService(route.params.id)
    if (result.code === 200) {
      const data = result.data
      notificationForm.value = {
        title: data.title || '',
        summary: data.summary || '',
        content: data.content || ''
      }
      
      // 内容已通过 v-model 绑定，无需手动设置
    }
  } catch (error) {
    console.error('加载通知详情失败:', error)
    showMessageToast('加载通知详情失败', 'error')
  }
}

// 页面初始化
onMounted(() => {
  if (!tokenStore.token) {
    router.push('/login')
    return
  }
  
  // wangEditor 通过 v-model 自动绑定，无需手动初始化
  
  // 编辑模式下加载数据
  loadNotificationDetail()
})

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})
</script>

<style scoped>
@import '@/assets/css/Publish.css';
</style>